﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFWS.XHandler.Core;
using JKF.Substructure;
using JKF.BusinessLayer.BLL;
using JKF.Entities;
using System.Data;
using JKF.Entities.Model;
namespace JKF.HandlerLayer.Sys
{
    public partial class SysUserHandler:AHttpHandler
    {
        private static bllSYS_USER bllSys_user = new bllSYS_USER();
        //private class SYS_USER_Module
        //{
        //    public string USER_KEY { get; set; }
        //    public string ACCOUNT { get; set; }
        //    public string REAL_NAME { get; set; }
        //    public string PWD { get; set; }
        //    public string AVAILABLE { get; set; }
        //    public string ROLE_KEY { get; set; }
        //    public string PHONE { get; set; }
        //    public string GENDER { get; set; }
        //    public string SHOP_CODE { get; set; }
        //    public string MOBILE { get; set; }
             
        //}
        public override void ProcessRequest()
        {
            //所有错误和异常将抛出异常.正常执行程序则在方法则返回数据
            try
            {
                this.Manager(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                //写日志
                AppLogger.Log(ex.Message, ex);
            }
        }
        #region 以前的根据区域来添加用户角色
        /*
        /// <summary>
        /// 添加账户
        /// </summary>
        public void InsertUser()
        {
            try
            {
                var strScr = P("moduleObj");
                string user_key = string.Empty;
                string user_shopInsert = this.BuildRole_Module_RoleInsert(JsonSerializer.Deserialize<SYS_USERinfo>(strScr), ref user_key);
                //return;
                // 账户添加事件，同时需要添加两个个表中的数据sys_user，dbo.SYS_USER_SHOP 采用事务  
                bllSys_user.TransactionInsertORUpdateUser_ShopBLL(user_shopInsert);
                //bllDic_Level.Add(dic_LevelInfo);
                var pk = user_key;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "添加成功.", Data = pk }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 修改账户信息
        /// </summary>
        public void EditUser()
        {
            try
            {
                var strScr = P("moduleObj");
                string user_key = string.Empty;
                // 角色修改事件，同时需要修改三个表中的数据sys_role_action，sys_role_module，sys_role 采用事务  

                string user_shopUpdate = BuildSysUser_ShopUpdate(JsonSerializer.Deserialize<SYS_USERinfo>(strScr), ref user_key);
                // 执行脚本更新
                bool reslt = bllSys_user.TransactionInsertORUpdateUser_ShopBLL(user_shopUpdate);
                var pk = user_key;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "修改成功.", Data = pk, Success = reslt }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 从Json对象构建对象，用于Update
        /// </summary>
        /// <param name="shopInfo">实体对象</param>
        /// <param name="role_key">账户ID</param>
        /// <returns></returns>
        public string BuildSysUser_ShopUpdate(SYS_USERinfo userinfo, ref string user_key)
        {
            StringBuilder builder = new StringBuilder();
            //user_key = DB.HR.GetNewGuid(); // 角色表中的主键ID
            user_key = userinfo.USER_KEY.ToString();
            // 1.先生成用户表sys_user中的insert语句
            builder.AppendFormat(@"UPDATE dbo.SYS_USER SET ACCOUNT='{0}',REAL_NAME='{1}',GENDER='{2}',PHONE='{3}',
MOBILE='{4}',ROLE_KEY='{5}',AVAILABLE='{6}',SHOP_CODE='{7}',DATE_UPDATE='{8}',ADMIN_AREAS='{9}'", userinfo.ACCOUNT, userinfo.REAL_NAME, userinfo.GENDER, userinfo.PHONE, userinfo.MOBILE, userinfo.ROLE_KEY, userinfo.AVAILABLE, userinfo.SHOP_CODE, DateTime.Now.ToString(), userinfo.ADMIN_AREAS.TrimEnd(','));
            if (!string.IsNullOrEmpty(userinfo.PWD))
            {
                builder.AppendFormat(",PWD='{0}'", userinfo.PWD);
            }
            builder.AppendFormat(" WHERE USER_KEY='{0}'", user_key);
            //2 判断当前选择的角色是总店，还是区域 
            SYS_ROLEinfo roleInfo = new bllSYS_ROLE().GetModel(userinfo.ROLE_KEY);

            //3.生成dbo.SYS_USER_SHOP表的delete和Insert语句
            //先删除dbo.SYS_USER_SHOP表中数据
            builder.AppendFormat(" \r\n  DELETE dbo.SYS_USER_SHOP WHERE USER_KEY='{0}' \r\n", user_key);
            if (roleInfo.ROLE_NAME.Contains(SysConfig.HeadShop))
            {
                builder.AppendFormat(@"INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)
SELECT '{0}',SHOP_CODE,'{1}','{2}','{3}' FROM SHOP ", user_key, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
            }
            else if (roleInfo.ROLE_NAME.Contains(SysConfig.AreaShop))
            {
                //如果是区域管理员，先获取到选中的区域，然后组装条件
                string[] admin_areas = userinfo.ADMIN_AREAS.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                string condition = string.Empty;
                for (int i = 0; i < admin_areas.Length; i++)
                {
                    condition += string.Format(" area_code like '%{0}___%' or ", admin_areas[i].Substring(0, 3));
                }
                builder.AppendFormat(@"INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE) 
select '{0}',shop_code,'{1}','{2}','{3}' from shop where {4}", user_key, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString(), condition.Remove(condition.IndexOf("or", condition.Length - 4)));
            }
            else
            {// 普通
                builder.AppendFormat(@"INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)
VALUES('{0}','{1}','{2}','{3}','{4}') ", user_key, userinfo.SHOP_CODE, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
            }
            return builder.ToString();
        }

        /// <summary>
        /// 从Json对象构建对象，用于Insert
        /// </summary>
        /// <param name="shopInfo">实体对象</param>
        /// <param name="role_key">角色ID</param>
        /// <returns></returns>
        public string BuildRole_Module_RoleInsert(SYS_USERinfo userinfo, ref string user_key)
        {
            StringBuilder builder = new StringBuilder();
            user_key = DB.HR.GetNewGuid(); // 角色表中的主键ID
            // 1.先生成用户表sys_user中的insert语句
            builder.AppendFormat("INSERT INTO dbo.SYS_USER(USER_KEY, ACCOUNT, PWD, REAL_NAME, GENDER, PHONE, MOBILE, ROLE_KEY, AVAILABLE, SHOP_CODE,DATE_CREATE,DATE_UPDATE,ADMIN_AREAS) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}');", user_key, userinfo.ACCOUNT, userinfo.PWD, userinfo.REAL_NAME, userinfo.GENDER, userinfo.PHONE, userinfo.MOBILE, userinfo.ROLE_KEY, userinfo.AVAILABLE, userinfo.SHOP_CODE, DateTime.Now.ToString(), DateTime.Now.ToString(), userinfo.ADMIN_AREAS.TrimEnd(','));
            //2 判断当前选择的角色是总店，还是区域 
            SYS_ROLEinfo roleInfo = new bllSYS_ROLE().GetModel(userinfo.ROLE_KEY);

            //3.生成dbo.SYS_USER_SHOP表的Insert语句
            if (roleInfo.ROLE_NAME.Contains(SysConfig.HeadShop))
            {
                builder.AppendFormat(@"INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)
SELECT '{0}',SHOP_CODE,'{1}','{2}','{3}' FROM SHOP ", user_key, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
            }
            else if (roleInfo.ROLE_NAME.Contains(SysConfig.AreaShop))
            {
                //如果是区域管理员，先获取到选中的区域，然后组装条件
                string[] admin_areas = userinfo.ADMIN_AREAS.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                string condition = string.Empty;
                for (int i = 0; i < admin_areas.Length; i++)
                {
                    condition += string.Format(" area_code like '%{0}___%' or ", admin_areas[i].Substring(0, 3));
                }
                builder.AppendFormat(@"INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE) 
select '{0}',shop_code,'{1}','{2}','{3}' from shop where {4}", user_key, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString(), condition.Remove(condition.IndexOf("or", condition.Length - 4)));
            }
            else
            {// 普通
                builder.AppendFormat(@"INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)
VALUES('{0}','{1}','{2}','{3}','{4}') ", user_key, userinfo.SHOP_CODE, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
            }
            return builder.ToString();
        }  
        */
        #endregion

        #region 现在添加用户页面可以为其分配管理店铺
        /// <summary>
        /// 添加账户
        /// </summary>
        public void InsertUser()
        {
            try
            {
                var strScr = P("moduleObj");
                string user_key = string.Empty;
                string user_shopInsert = this.BuildRole_Module_RoleInsert(JsonSerializer.Deserialize<SYS_USERinfo>(strScr), ref user_key);
                //return;
                // 账户添加事件，同时需要添加两个个表中的数据sys_user，dbo.SYS_USER_SHOP 采用事务  
                bllSys_user.TransactionInsertORUpdateUser_ShopBLL(user_shopInsert);
                //bllDic_Level.Add(dic_LevelInfo);
                var pk = user_key;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "添加成功.", Data = pk }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 修改账户信息
        /// </summary>
        public void EditUser()
        {
            try
            {
                var strScr = P("moduleObj");
                string user_key = string.Empty;
                // 角色修改事件，同时需要修改三个表中的数据sys_role_action，sys_role_module，sys_role 采用事务  

                string user_shopUpdate = BuildSysUser_ShopUpdate(JsonSerializer.Deserialize<SYS_USERinfo>(strScr), ref user_key);
                //return;
                // 执行脚本更新
                bool reslt = bllSys_user.TransactionInsertORUpdateUser_ShopBLL(user_shopUpdate);
                var pk = user_key;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "修改成功.", Data = pk, Success = reslt }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 从Json对象构建对象，用于Update
        /// </summary>
        /// <param name="shopInfo">实体对象</param>
        /// <param name="role_key">账户ID</param>
        /// <returns></returns>
        public string BuildSysUser_ShopUpdate(SYS_USERinfo userinfo, ref string user_key)
        {
            StringBuilder builder = new StringBuilder();
            user_key = userinfo.USER_KEY.ToString();
            // 1.先生成用户表sys_user中的insert语句
            builder.AppendFormat(@"UPDATE dbo.SYS_USER SET ACCOUNT='{0}',REAL_NAME='{1}',GENDER='{2}',PHONE='{3}',
MOBILE='{4}',ROLE_KEY='{5}',AVAILABLE='{6}',SHOP_CODE='{7}',DATE_UPDATE='{8}',ADMIN_AREAS='{9}'", userinfo.ACCOUNT, userinfo.REAL_NAME, userinfo.GENDER, userinfo.PHONE, userinfo.MOBILE, userinfo.ROLE_KEY, userinfo.AVAILABLE, userinfo.SHOP_CODE, DateTime.Now.ToString(), userinfo.ADMIN_AREAS.TrimEnd(','));
            if (!string.IsNullOrEmpty(userinfo.PWD))
            {
                builder.AppendFormat(",PWD='{0}'", userinfo.PWD);
            }
            builder.AppendFormat(" WHERE USER_KEY='{0}'", user_key);
            //2 判断当前选择的角色是，还是区域 
            SYS_ROLEinfo roleInfo = new bllSYS_ROLE().GetModel(userinfo.ROLE_KEY);
            //3.生成dbo.SYS_USER_SHOP表的delete和Insert语句
            //先删除dbo.SYS_USER_SHOP表中数据
            builder.AppendFormat(" \r\n  DELETE dbo.SYS_USER_SHOP WHERE USER_KEY='{0}' \r\n", user_key);
            if (SysConfig.HeadShop.Contains(roleInfo.ROLE_NAME))
            {
                builder.AppendFormat(@"INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)
SELECT '{0}',SHOP_CODE,'{1}','{2}','{3}' FROM SHOP ", user_key, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
            }
            else if (SysConfig.AreaShop.Contains(roleInfo.ROLE_NAME))
            { //|| roleInfo.ROLE_NAME.Contains(SysConfig.Majordomo)
                //如果是区域或者总监管理员，先获取到选中的店铺，然后组装条件
                string[] admin_shops = base.P("AdminShop").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < admin_shops.Length; i++)
                {
                    builder.AppendFormat(@" INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)  VALUES('{0}','{1}','{2}','{3}','{4}'); ", user_key, admin_shops[i], bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
                }
                //最后再加上它所属店铺(不应该加上，否则会出现问题)
                //                builder.AppendFormat(@" INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)
                //VALUES('{0}','{1}','{2}','{3}','{4}'); ", user_key, userinfo.SHOP_CODE, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
            }
            else if (SysConfig.LocalShop.Contains(roleInfo.ROLE_NAME) || SysConfig.OperatorShop.Contains(roleInfo.ROLE_NAME))
            {// 普通 
                builder.AppendFormat(@"INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)
VALUES('{0}','{1}','{2}','{3}','{4}') ", user_key, userinfo.SHOP_CODE, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
            }
            return builder.ToString();
        }

        /// <summary>
        /// 从Json对象构建对象，用于Insert
        /// </summary>
        /// <param name="shopInfo">实体对象</param>
        /// <param name="role_key">角色ID</param>
        /// <returns></returns>
        public string BuildRole_Module_RoleInsert(SYS_USERinfo userinfo, ref string user_key)
        {
            StringBuilder builder = new StringBuilder();
            user_key = DB.HR.GetNewGuid(); //  
            // 1.先生成用户表sys_user中的insert语句
            builder.AppendFormat("INSERT INTO dbo.SYS_USER(USER_KEY, ACCOUNT, PWD, REAL_NAME, GENDER, PHONE, MOBILE, ROLE_KEY, AVAILABLE, SHOP_CODE,DATE_CREATE,DATE_UPDATE,ADMIN_AREAS) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}'); ", user_key, userinfo.ACCOUNT, userinfo.PWD, userinfo.REAL_NAME, userinfo.GENDER, userinfo.PHONE, userinfo.MOBILE, userinfo.ROLE_KEY, userinfo.AVAILABLE, userinfo.SHOP_CODE, DateTime.Now.ToString(), DateTime.Now.ToString(), userinfo.ADMIN_AREAS.TrimEnd(','));
            //2 判断当前选择的角色是总店，还是区域 
            SYS_ROLEinfo roleInfo = new bllSYS_ROLE().GetModel(userinfo.ROLE_KEY);

            //3.生成dbo.SYS_USER_SHOP表的Insert语句
            if (SysConfig.HeadShop.Contains(roleInfo.ROLE_NAME))
            {
                builder.AppendFormat(@" INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)
SELECT '{0}',SHOP_CODE,'{1}','{2}','{3}'  FROM SHOP ", user_key, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
            }
            else if (SysConfig.AreaShop.Contains(roleInfo.ROLE_NAME))
            {//|| roleInfo.ROLE_NAME.Contains(SysConfig.Majordomo)
                //如果是区域或者总监管理员，先获取到选中管理的店铺，然后组装条件
                string[] admin_shops = base.P("AdminShop").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < admin_shops.Length; i++)
                {
                    builder.AppendFormat(@" INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)  VALUES('{0}','{1}','{2}','{3}','{4}'); ", user_key, admin_shops[i], bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
                }
                //最后再加上它所属店铺(不应该加上，否则会出现问题)
                //                builder.AppendFormat(@" INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)
                //VALUES('{0}','{1}','{2}','{3}','{4}'); ", user_key, userinfo.SHOP_CODE, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
            }
            else if (SysConfig.LocalShop.Contains(roleInfo.ROLE_NAME) || SysConfig.OperatorShop.Contains(roleInfo.ROLE_NAME))
            {// 普通：店长和操作员
                builder.AppendFormat(@"INSERT INTO SYS_USER_SHOP(USER_KEY,SHOP_CODE,USER_CREATE,DATE_CREATE,DATE_UPDATE)
VALUES('{0}','{1}','{2}','{3}','{4}') ", user_key, userinfo.SHOP_CODE, bllSYS_USER.CurrentUser.USER_KEY.ToString(), DateTime.Now.ToString(), DateTime.Now.ToString());
            }
            return builder.ToString();
        } 
        #endregion  
        /// <summary>
        /// 根据账户ID获得实体模块信息
        /// </summary>
        public void GetUserByCode()
        {
            try
            {
                var scid = P("moduleKey");
                SYS_USERinfo userInfo = bllSys_user.GetModel(new Guid(scid));
                SHOPinfo shopInfo = new bllSHOP().GetModel(userInfo.SHOP_CODE);// 获取店面信息
                userInfo.ADMIN_AREAS = GetManagerShop(userInfo.USER_KEY);
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data =userInfo, Mode=shopInfo  }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
       
        /// <summary>
        /// 获取用户列表
        /// </summary>
        public void GetUsers()
        {
            var obj = new PagerList();

            int pageCount = 0;
            int rowCount = 0;
            //USER_KEY, ACCOUNT, PWD, REAL_NAME, GENDER, PHONE, MOBILE, ROLE_KEY, AVAILABLE, SHOP_CODE, DATE_CREATE, DATE_UPDATE 
            if (P("isExport") == "1")
            {//账号	所属角色	姓名	联系电话	手机	所属店面	状态	创建时间
                DataTable dt = bllSys_user.GetUsersBLL(bllSYS_USER.CurrentUser, P("ACCOUNT"), P("REAL_NAME"), P("ROLE_KEY"), P("SHOP_CODE"), P("AVAILABLE"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount); 
                IDictionary<string, string> columns = new Dictionary<string, string>();

                columns.Add("ACCOUNT", "账号");
                columns.Add("ROLE_KEY", "所属角色");
                columns.Add("REAL_NAME", "姓名");
                columns.Add("PHONE", "联系电话");
                columns.Add("MOBILE", "手机");
                columns.Add("SHOP_CODE", "所属店面");
                columns.Add("AVAILABLE", "状态");
                columns.Add("DATE_CREATE", "创建时间");
                Excel.Export("用户管理", dt, columns, Response, Excel.PageType.handler);
            }
            else
            {
                obj.Entity = from a in bllSys_user.GetUsersBLL(bllSYS_USER.CurrentUser, P("ACCOUNT"), P("REAL_NAME"), P("ROLE_KEY"), P("SHOP_CODE"), P("AVAILABLE"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount).AsEnumerable()
                             select new
                             {
                                 USER_KEY = a.Field<Guid>("USER_KEY"),
                                 ACCOUNT = a.Field<string>("ACCOUNT"),
                                 PWD = a.Field<string>("PWD"),
                                 REAL_NAME = a.Field<string>("REAL_NAME"),
                                 //GENDER = a.Field<char>("GENDER"),
                                 SHOP_CODE = a.Field<string>("SHOP_CODE"),
                                 PHONE = a.Field<string>("PHONE"),
                                 MOBILE = a.Field<string>("MOBILE"),
                                 ROLE_KEY = a.Field<string>("ROLE_KEY"), // 可能为空
                                 AVAILABLE = AVAILABLEToString(a.Field<string>("AVAILABLE")),
                                 DATE_CREATE = (a.Field<DateTime>("DATE_CREATE")).ToString("yyyy-MM-dd")
                             };

                obj.RowCount = rowCount;
                obj.PageCount = pageCount;
                ResponseJsonObject = obj;
            }
        }
         
        /// <summary>
        /// 账户是否有效转换中文0 不可用 1可用
        /// </summary>
        /// <returns></returns>
        private string AVAILABLEToString(string AVAILABLE)
        {
            switch (AVAILABLE)
            {
                case "0":
                    return "停用";
                     
                case "1":
                    return "启用"; 
                default:
                    return "未知"; 
            }
        }
        /// <summary>
        /// 判断账户是否存在
        /// </summary>
        public void CheckUserAccount()
        {
            try
            {
                var user_account = P("ACCOUNT");
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Data = bllSys_user.ExistsUserAccountBLL(user_account) }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 删除账户
        /// </summary>
        public void DeleteUser()
        {
            try
            {
                var user_key = P("id");
                // 删除账户时，需要判断是否可以删除？如果其他关联就不允许删除  
                //bllShop.Delete(shop_Code);
                // 返回1，表示可以删除，否则不允许删除
                string result = bllSys_user.SysUserDeleteBLL(user_key); 
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = result, Message=result, Data = user_key }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 修改密码 
        /// </summary>
        public void ChangePassWord()
        {
            string oldPwd = base.P("OldPwd");
            string newPwd = base.P("NewPwd");
            try
            {
                if (string.IsNullOrEmpty(oldPwd) || string.IsNullOrEmpty(newPwd))
                {
                    this.ResponseJsonObject = new { IsSucc = false, Message = "密码不能为空，请重新输入！" };
                    return;
                }
                if (oldPwd == newPwd)
                {
                    this.ResponseJsonObject = new { IsSucc = false,Message="原密码不能和新密码相同，请重新输入！" };
                    return;
                }
                if (bllSYS_USER.CurrentUser.PWD != oldPwd)
                {
                    this.ResponseJsonObject = new { IsSucc = false, Message = "原密码不正确，请重新输入！" };
                    return;
                }
                //获取到当前账户信息
                SYS_USERinfo model = bllSYS_USER.CurrentUser;
                model.PWD = newPwd;
                bllSys_user.Update(model);
                this.ResponseJsonObject = new
                {
                    IsSucc = true,
                    Message="修改成功！" 
                };
            }
            catch (Exception ex)
            {
                
                this.ResponseJsonObject = new
                    {
                        IsSucc = false ,
                        Message=ex.Message
                    };
            }
        }

        /// <summary>
        /// 获取店铺和省的关系树
        /// </summary>
        public void GetShopTree()
        {
            try
            {
                var oList = bllSys_user.GetShopProvinceTreeBLL();
                Response.Write(new ResponseInf
                {
                    Data = oList,
                    Success = true
                }.ToJson());
            }
            catch (Exception exp)
            {
                Response.Write(new ResponseInf { Success = false, Message = exp.Message }.ToJson());
            }
        }
 
        /// <summary>
        ///  获取区域经理和总监的管理的店铺
        /// </summary>
        /// <param name="user_key">用户key</param>
        /// <returns></returns>
        private string GetManagerShop(Guid user_key)
        {
            StringBuilder sb = new StringBuilder();
            var oList = new bllSYS_USER_SHOP().GetListArray(String.Format(" USER_KEY='{0}'",user_key.ToString()));
            for (int i = 0; i < oList.Count; i++)
            {
                sb.AppendFormat("{0},",oList[i].SHOP_CODE);
            }

            return sb.ToString().TrimEnd(',');
        }
    }
}
